// pages/certify/certify.js
var QQMapWX = require('../../qqmap-wx-jssdk.min.js');
 
// 实例化API核心类
var qqmapsdk = new QQMapWX({
    key: '6FTBZ-OPECR-OYVWT-WULAV-V7VPQ-FAFCT' // 必填
});

Page({

  data: {
    // 提示交货日期
    buytime:'',
    // 地址信息
    name:'',
    phone:'',
    address:'',
    way:'',
    // 物品信息
    pic:'',
    title:'',
    value:"",
    deposit:"",
    day:"",
    sum:'',
    // 租用时间
    starttime:'',
    finishtime:'2',
    // 订单信息
    orderid:'',
    ordertime:'',
    paytime:'',
    remark:'',
    // 快照照片
    buyarray:[],
    showpic:true,
    ismine:'',

    itemid:''
  },
  onLoad(options){
    var that = this;
    console.log(options)
    if(options.ismine == "true"){
      this.setData({
        ismine:true
      })
    }else{
      this.setData({
        ismine:false
      })
    }

    this.setData({
      orderid:options.orderid,
      itemid:options.itemid
    })

    if(options.orderid && options.itemid){
      wx.request({
        url: 'http://127.0.0.1:8080/order/orderById',
        method:"POST",
        data:{orderid:options.orderid},
        success(res){
          if(res.data){
            var data = res.data[0];
            that.setData({
              name:data.receiveName,
              phone:data.receivePhone,
              address:data.deliveryAddress,
              way:data.deliveryMethod,
              day:data.rentDays,
              sum:data.rentPayment,
              // 租用时间
              buytime:data.rentStartTime,
              starttime:data.rentStartTime,
              finishtime:data.rentEndTime,
              // 订单信息
              orderid:data.orderID,
              ordertime:data.orderGenTime,
              paytime:data.orderPayTime,
              remark:data.orderRemark,
            })
          }
          console.log(res)
        }
      })

      wx.request({
        url: 'http://127.0.0.1:8080/item/selectItemById',
        method:"POST",
        data:{itemid:options.itemid},
        success(res){
          // console.log(res)
          if(res.data){
            var data = res.data[0];
            data.itemPic = JSON.parse(data.itemPic)
            that.setData({
               // 物品信息
               pic:data.itemPic[0],
               title:data.itemTitle,
               value:data.dayRent,
               deposit:data.deposit,
            })
          }
        }
      })

    }

    if(this.data.buyarray.length != 0){
      this.setData({
        showpic:false
      })
    }
  },

// 添加商品快照
  addpic(e){
    let that = this;
    wx.chooseImage({
      count: 9,
      success(res){
        var buyarray = that.data.buyarray.concat(res.tempFilePaths)
        // console.log(buyarray)
        that.setData({
          buyarray:buyarray,
          showpic:false
        })
      }
    })
  },
  //删除照片
  delpic(e){
    // console.log(e)
    let that = this;
    var index = e.currentTarget.dataset.index;
    var del = this.data.buyarray
    wx.showModal({
      content: '是否删除该照片',
      title: '提示',
      success(res){
        if(res.confirm){
          del.splice(index,1)
          var len = del.length
          if(len == 0){
            that.setData({
              showpic:true
            })
          }
          that.setData({
            buyarray:del
          })
        }
      },
    })
    
  },
  // 查看图片
  showpic(e){
    var index  =e.currentTarget.dataset.index;
    wx.previewImage({
      current: this.data.buyarray[index],     //当前图片地址
      urls: this.data.buyarray,                 //所有要预览的图片的地址集合 数组形式
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  // 展示地址
  showaddress(e){
    var _this = this;
    //调用地址解析接口
    qqmapsdk.geocoder({
      //获取表单传入地址
      address: _this.data.address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
      success: function(res) {//成功后的回调
        console.log(res);
        var res = res.result;
        var latitude = res.location.lat;
        var longitude = res.location.lng;
        //根据地址解析在地图上标记解析地址位置
        _this.setData({ // 获取返回结果，放到markers及poi中，并在地图展示
          markers: [{
            id: 0,
            title: res.title,
            latitude: latitude,
            longitude: longitude,
            iconPath: '/pic/地标.png',//图标路径
            width: 30,
            height: 30,
            // callout: { //可根据需求是否展示经纬度
            //   content: latitude + ',' + longitude,
            //   color: '#000',
            //   display: 'ALWAYS'
            // }
          }],
          poi: { //根据自己data数据设置相应的地图中心坐标变量名称
            latitude: latitude,
            longitude: longitude
          },
        });

        wx.openLocation({
          latitude:latitude,
          longitude:longitude,
          address: _this.data.address,
          name: _this.data.address,
          scale: 28,
        })
      },
      fail: function(error) {
        console.error(error);
      },
      complete: function(res) {
        console.log(res);
      }
    })
  },
  // 联系电话
  callrent(){
    wx.makePhoneCall({
      phoneNumber: this.data.phone,
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  callregulor(){
    wx.makePhoneCall({
      phoneNumber: '1025555555',
      success: (res) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },

  //确认交货
  finishchange(){
    var that = this;
    var pics = this.data;
    // console.log(this.data)
    if(pics!=0){
      wx.showModal({
        title:'确定已经收到货',
        content: '',
        complete: (res) => {
        if (res.confirm) {
            //上传完成后把文件上传到服务器
          var arr = []
          var  h = this.data.buyarray.length;
          var i =0;
          for (i = 0; i < h; i++) {
          //上传文件
          // console.log(i,h)
            wx.uploadFile({
            url: 'http://127.0.0.1:8080/image/upload',
            filePath: this.data.buyarray[i],
              name: "file",
              header: {
                "content-type": "multipart/form-data"
              },
              success: function ({ data: res }) {
                // console.log(res)
                res = JSON.parse(res);
                const pic_url = 'http://127.0.0.1:8080/image/download?name=' + res.data
                // console.log(pic_url)
                // 图片路径集合
                arr.unshift(pic_url);
              },
              fail: function (err) {
                wx.showToast({
                  title: "上传失败",
                  icon: "error",
                  duration: 2000
                })
              },
              complete: function (result) {
                // console.log(result.errMsg)
              }
            })
          }

          setTimeout(function(){
            // 当前时间
            // console.log("48586546568768756")
            // console.log(arr)
            var changeItemTime = new Date().toJSON().substring(0, 10) + ' ' + new Date().toTimeString().substring(0,8);
            var data = {
              orderid:that.data.orderid,
              itempic:JSON.stringify(arr),
              deliverytime:changeItemTime,
            }
            // console.log(data)
            wx.request({
              url: 'http://127.0.0.1:8080/order/updateToInRent',
              method:"POST",
              data:data,
              success(res){
                // console.log(res)
                if(res.data){
                  wx.request({
                    url: 'http://127.0.0.1:8080/item/addrenttimes',
                    method:"POST",
                    data:{itemid:that.data.itemid},
                    success(res){
                      
                    }
                  })

                  wx.showToast({
                    title: '发布成功',
                    duration: 1000,
                    icon: "success",
                    success: (res) => {},
                  })
                  wx.navigateBack({
                    delta: 2
                  });
                }else{
                  wx.showToast({
                    title: '发布失败',
                    duration: 1000,
                    icon: "error",
                    success: (res) => {},
                  })
                }
              }
            }) 
          },100)
          }
        }
      })


    }else{
      wx.showToast({
        title: '缺少物损照片，在售后可以作为证明',
        duration: 1500,
        icon: "none",
      })
    }

  },
  //退款
  backmoney(){
    var that = this;
    wx.showModal({
      title: '确定要退款吗?',
      complete: (res) => {
        if (res.confirm) {
          var money = that.data.sum;
          wx.request({
            url: 'http://127.0.0.1:8080/user/personInfo',
            method:"POST",
            data:{openid:wx.getStorageSync('openid')},
            success(res){
              if(res.data[0]){
                var sum = money + res.data[0].money;
                //退回价钱
                wx.request({
                  url: 'http://127.0.0.1:8080/user/updateMoney',
                  method:"POST",
                  data:{openid:wx.getStorageSync('openid'),
                        money:sum},
                  success(res){
                    if(res.data){
                      wx.request({
                        url: 'http://127.0.0.1:8080/user/updateMoney',
                        method:"POST",
                        data:{openid:wx.getStorageSync('openid'),
                              money:sum},
                        success(res){
                          if(res.data){
                            wx.request({
                              url: 'http://127.0.0.1:8080/item/renewItem',
                              method:"POST",
                              data:{itemid:that.data.itemid},
                              success(res){
                                if(res.data){
                                  
                                }
                                // console.log(res)
                              }
                            }) 
                          }
                        }
                      })
                    }
                    // console.log(res)
                  }
                })
              }
            }
          })

          //删除该订单
          wx.request({
            url: 'http://127.0.0.1:8080/order/delNoPay',
            method:"POST",
            data:{orderid:that.data.orderid},
            success(res){
              // console.log(res);
              if(res.data){
                wx.navigateBack({
                  delta: 2,
                  success: (res) => {
                    wx.showToast({
                      title: '退款成功',
                    })
                  },
                })
              }
            }
          })

        }
      }
    })
  }

})